package com.jf.mall.service;

import com.jf.mall.dao.CommodityDAO;
import com.jf.mall.dao.FurnitureDAO;
import com.jf.mall.dao.impl.CommodityImpl;
import com.jf.mall.dao.impl.FurnitureImpl;
import com.jf.mall.domain.Commodity;
import com.jf.mall.domain.Furniture;
import com.jf.mall.domain.ShoppingCart;
import com.jf.mall.domain.User;

import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-10-02
 * Time:5:27
 */
public class ShoppingCartService {
    private final FurnitureDAO furnitureDAO = new FurnitureImpl();
    private final CommodityDAO commodityDAO = new CommodityImpl();

    public void addCommodity(int id, ShoppingCart shoppingCart) {
        Furniture furniture = furnitureDAO.queryFurnitureById(id);
        if (furniture == null || furniture.getStock() <= 0) {
            return;
        }
        Integer userId = shoppingCart.getUserId();
        if (userId != null) {
            if (shoppingCart.contains(id)) {
                shoppingCart.addCommodity(id, furniture);
                Commodity commodity = shoppingCart.getCommodity(id);
                commodityDAO.updateCommodity(commodity);
            } else {
                shoppingCart.addCommodity(id, furniture);
                Commodity commodity = shoppingCart.getCommodity(id);
                commodityDAO.addCommodity(commodity);
            }
        } else {
            shoppingCart.addCommodity(id, furniture);
        }
    }

    public void deleteCommodity(int id, ShoppingCart shoppingCart) {
        Integer userId = shoppingCart.getUserId();
        if (userId != null && shoppingCart.contains(id)) {
            Commodity commodity = shoppingCart.getCommodity(id);
            commodityDAO.deleteCommodity(commodity.getId());
        }
        shoppingCart.removeCommodity(id);
    }

    public void updateCommodityCount(int id, ShoppingCart shoppingCart, int count) {
        shoppingCart.updateCommodityCount(id, count);
        Integer userId = shoppingCart.getUserId();
        if (userId != null && shoppingCart.contains(id)) {
            Commodity commodity = shoppingCart.getCommodity(id);
            commodityDAO.updateCommodity(commodity);
        }

    }

    public void updateShoppingCart(ShoppingCart shoppingCart) {
        Integer userId = shoppingCart.getUserId();
        if (userId != null) {
            List<Commodity> commodities = commodityDAO.getCommoditiesByUserId(userId);
            shoppingCart.updateCart(commodities);
        } else {
            Integer[] ids = shoppingCart.getIds();
            if (!(ids == null || ids.length == 0)) {
                Map<Integer, Furniture> furnitureMap = furnitureDAO.queryFurnitureMapByIds(ids);
                shoppingCart.updateCart(furnitureMap);
            }
        }
    }
    public void clearUserShoppingCart(User user) {
        commodityDAO.deleteUserCommodities(user.getId());
    }
}
